

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.SocketChannel;
import java.util.Iterator;
import java.util.Set;

public class CSocketClientDemo2 {
    /**
     * @param args
     * @throws IOException
     */
    public static void main(String[] args) throws IOException{
        Selector selc = Selector.open();  //创建选择器
        SocketChannel sc = SocketChannel.open();
        sc.configureBlocking(false);
        sc.register(selc, SelectionKey.OP_CONNECT|SelectionKey.OP_READ|SelectionKey.OP_WRITE);    //注册connect和read和write这些事件
        sc.connect(new InetSocketAddress("127.0.0.1",9999));   //指定监听端口
        while(true){
            int selcCont = selc.select();
            if(selcCont > 0){
                Set<SelectionKey> set = selc.selectedKeys();
                Iterator<SelectionKey>it = set.iterator();
                while (it.hasNext()){
                    SelectionKey sk = it.next();
                    SocketChannel scx = (SocketChannel)sk.channel();     //获取sk对应的通道
                    if(sk.isConnectable()){
                        scx.finishConnect(); //完成连接
                        scx.register(selc, SelectionKey.OP_WRITE);
                    }else if (sk.isWritable()){
                        StringBuffer sb = new StringBuffer();
                        String str = "数据";
                        String sendStr = str.getBytes().length+"\r\n"+str;

                        ByteBuffer buf = ByteBuffer.wrap(sendStr.getBytes());  //发送数据
                        while(buf.hasRemaining()){
                            scx.write(buf);
                        }
                        scx.register(selc,sk.interestOps() & ~SelectionKey.OP_WRITE); //取消write注册 ~是取反 &是与
                    }else if(sk.isReadable()){
                        System.out.println("开始读");
                        ByteBuffer temp = ByteBuffer.allocate(1);
                        String head = "";
                        while (!head.endsWith("\r\n")){     //添加数据包分割符
                            sc.read(temp);
                            head += new String(temp.array());
                            temp.clear();
                        }
                        int len = Integer.parseInt(head.substring(0,head.length()-2));
                        ByteBuffer buf = ByteBuffer.allocate(len);

                        while(buf.hasRemaining()){
                            sc.read(buf);       //把数据填充到缓冲区
                        }
                        String msg = new String(buf.array(),"utf-8");
                        System.out.println("收到服务器发回的消息："+msg);
                    }
                }
                it.remove();
            }
        }
    }
}